package com.hhz.springcloud.alibaba.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhz.springcloud.alibaba.mapper.OrderMapper;
import com.hhz.springcloud.alibaba.pojo.Order;
import com.hhz.springcloud.alibaba.service.OrderService;
import com.hhz.springcloud.alibaba.service.openFeign.AcccountService;
import com.hhz.springcloud.alibaba.service.openFeign.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author Rem
 * @Date 2020-03-19
 */

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    //账户
    @Autowired
    private AcccountService acccountService;

    //库存
    @Autowired
    private StorageService storageService;

    /**
     * 新增订单  调用库存服务做扣减库存，调用账户服务扣减余额==》修改订单状态
     *
     * @param order
     * @return
     */
    /**
     * 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态
     * 简单说：下订单->扣库存->减余额->改状态
     */
    @Override
    @GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
    public Integer addOrder(Order order) {
        log.info("------>开始新建订单");
        baseMapper.insert(order);

        log.info("------>订单微服务开始调用库存，做扣减count===start");
        storageService.decreaseStorage(order.getProductId(), order.getCount());
        log.info("------>订单微服务开始调用库存，做扣减count===end");

        log.info("------>订单微服务开始调用账户，做扣减money===start");
        acccountService.decreaseAccount(order.getUserId(), order.getMoney());
        log.info("------>订单微服务开始调用账户，做扣减money===end");

        //0进行中   1已完成
        System.err.println("id:"+order.getId());
        log.info("------>修改订单状态");
        return updateOrder(order.getId(), 1);
    }

    /**
     * 修改订单状态
     *
     * @param order
     * @return
     */
    @Override
    public Integer updateOrder(Long id, int status) {

        UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
        wrapper.set("status", status).eq("id", id);
       return baseMapper.update(null, wrapper);

    }
}

